import Vue from "vue"
import VueRouter from "vue-router"
import axios from "axios"
import store from "../store"
import Cookie from "js-cookie"
import Elmentui from "element-ui"
Vue.use(VueRouter);

const routes = [{
    path: "/",
    redirect: "/login"
  }, {
    path: '/login',
    name: "login",
    component: _ => import("@/views/login/index.vue")
  },
  {
    path: "/home",
    name: "Home",
    component: _ => import("@/views/home/index"),
    children: []
  }, {
    path: '/Visualizations',
    name: "Visualizations",
    component: _ => import("@/views/Visualizations/index.vue")
  },
]

const router = new VueRouter({
  mode: "history",
  routes
})

router.beforeEach((to, from, next) => {
  let hasRouters = store.state.menu.hashRouter
  if(store.state.menu.menuList.length==0){
    if(to.path != from.path)axios.get("/api/menu/nav").then(res => {
      if (res.code == 200) {
        let arr = []
        res.data.menuList.map(item => { //动态创建路由表
          let result = createRoute(item)
          if (Array.isArray(result)) arr.push(...result);
          else arr.push(result)
        })
        routes[2].children = arr
        routes[2].children.push({
          path: "modify",
          name: "modify",
          component: _ => import("@/views/modify/index")
        })
        routes.push({
          path: "*",
          name: "NotFount",
          component: _ => import("@/views/error/index.vue")
        })
        store.commit("setHashRouter", true)
        router.matcher=new VueRouter().matcher
        router.addRoutes(routes)
        store.commit("setMenuList", res.data.menuList)
        store.commit("setAuthList", res.data.authList)

      }else if(res.code==401){
        // Elmentui.Message.warning(res.msg)
      }
    })
  }else{
    next()
  }
  next()
})

function createRoute(data) {
  if (data.children && data.type == 0) {
    let arr = []
    data.children.map(item => {
      arr.push(createRoute(item))
    })
    return arr
  } else {
    return {
      path: data.component.toLocaleLowerCase(),
      name: data.component,
      component: () => import("@/views/" + data.component.toLocaleLowerCase() + "/index.vue")
    }
  }
}
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
